package com.sgb.kjwl.view.ui.fragment.machine;

import androidx.databinding.DataBindingUtil;

import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentAskLeaseBinding;
import com.sgb.kjwl.di.machine.DaggerMachineFragComponent;
import com.sgb.kjwl.di.machine.MachineFragModule;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.lease.AskLeaseItemEntity;
import com.sgb.kjwl.model.entity.lease.AskLeaseSheBeiEntity;
import com.sgb.kjwl.model.entity.supplier3.DictEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.adapter.machine.AskLeaseAdapter;
import com.sgb.kjwl.view.widget.DictWindow5;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.view.widget.lease.LeaseAskMapPopWindow;
import com.sgb.kjwl.viewmodel.machine.AskLeaseFragModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class AskLeaseFragment extends AppLazyFragment {

    private FragmentAskLeaseBinding binding;

//    private List<BaseAreaEntity<List<BaseAreaEntity>>> cityDatas = new ArrayList<>();

    private String classNo = "";
    private String typeNo = "";
    private String sortNo = "1";
    private String provinceNo = "";
    private String cityNo = "";
    private String provinceName = "";
    private String cityName = "";
    //    private List<String> addrNo = new ArrayList<>();
    private String addrNo = "";

    //    private LeaseAskMapPopWindow classPopWindow;
    private LeaseAskMapPopWindow typePopWindow;
    private DictWindow5 sortPopWindow;
    //    private MultiLevelAreaPopWindow areaWindow;
    private ThreeLevelAreaWindow mAddressPop;

    private int page = 1;
    private boolean isLoadMore = false;
    private AskLeaseAdapter askLeaseAdapter;
    private String categoryType = "";
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;//省市区
    private List<AskLeaseItemEntity<List<AskLeaseItemEntity>>> allDatas;
    private List<PickSelectEntity> classDatas;
    private List<PickSelectEntity> typeDatas;
    private List<DictEntity3> sortDatas;

    @Inject
    AskLeaseFragModel askLeaseFragModel;
    private boolean isFilter = true;

    public static AskLeaseFragment newInstance(String type, ArrayList<AskLeaseItemEntity<List<AskLeaseItemEntity>>> list, boolean isFilter) {
        AskLeaseFragment fragment = new AskLeaseFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        bundle.putSerializable("data", list);
        bundle.putBoolean("isFilter", isFilter);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMachineFragComponent.builder().appComponent(appComponent).machineFragModule(new MachineFragModule(this)).build().inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_ask_lease, container, false);
        return binding.getRoot();
    }

    @Override
    protected void onLazyLoad() {
        if (getArguments() != null) {
            categoryType = getArguments().getString("type");
            isFilter = getArguments().getBoolean("isFilter", true);
        }
        if (!TextUtils.isEmpty(categoryType)) {
            allDatas = (ArrayList<AskLeaseItemEntity<List<AskLeaseItemEntity>>>) getArguments().getSerializable("data");
        } else {
            allDatas = new ArrayList<>();
            binding.tabLayout.setVisibility(View.GONE);
            binding.typeLayout.setVisibility(View.GONE);
        }
        if (!isFilter) {
            binding.roomLayout.setVisibility(View.GONE);
            binding.tabType.setVisibility(View.GONE);
        }
        initData();
    }

    //initView()执行在onLazyLoad之前
    @Override
    protected void initView() {
        initTabType();
        binding.classifyLayout.setOnClickListener(this);
        binding.typeLayout.setOnClickListener(this);
        binding.areaLayout.setOnClickListener(this);
        binding.sortLayout.setOnClickListener(this);

        if (askLeaseAdapter == null) {
            askLeaseAdapter = new AskLeaseAdapter(getActivity(), null);
        }
        binding.recyclerView.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0,
                getActivity().getResources().getDimension(R.dimen.dp2),
                getActivity().getResources().getColor(R.color.color_F5F5F5)));
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setAdapter(askLeaseAdapter);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                isLoadMore = false;
                page = 1;
                getData();
            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                page = page + 1;
                getData();
            }
        });

        askLeaseAdapter.setOnItemClick(new AdapterOnItemClick<AskLeaseSheBeiEntity>() {
            @Override
            public void onItemClick(AskLeaseSheBeiEntity entity, int p) {
                if (!ClickUtils.isDoubleClick()) {
                    askLeaseFragModel.getH5Url(entity.getType(), entity.getId());
                }
            }
        });

//        classPopWindow = new LeaseAskMapPopWindow(getActivity());
//        classPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
//            @Override
//            public void result(Object key1, Object key2, Object key3) {
//                updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 2, ((PickSelectEntity) key1).getPickerViewText());
//                classNo = ((PickSelectEntity) key1).getNo();
//                if (TextUtils.isEmpty(classNo)) {
//                    typeDatas.clear();
//                    PickSelectEntity entity = new PickSelectEntity();
//                    entity.setNo("");
//                    entity.setProjectscale("不限");
//                    typeDatas.add(0, entity);
//                    typePopWindow.goodsTypeAdapter.setDefItem(0);
//                } else {
//                    int classIndex = (int) key2;
//                    typeDatas.clear();
//                    if ("2".equals(categoryType)) {
//                        typeDatas.addAll(getCarByTypeData());
//                    } else {
//                        for (AskLeaseItemEntity<List<AskLeaseItemEntity>> ll : allDatas.get(classIndex - 1).getChildren()) {
//                            PickSelectEntity child = new PickSelectEntity();
//                            child.setNo(ll.getNo());
//                            child.setProjectscale(ll.getName());
//                            typeDatas.add(child);
//                        }
//                    }
//
//                    PickSelectEntity entity = new PickSelectEntity();
//                    entity.setNo("");
//                    entity.setProjectscale("不限");
//                    typeDatas.add(0, entity);
//                    typePopWindow.goodsTypeAdapter.setDefItem(0);
//                }
//                isLoadMore = false;
//                page = 1;
//                typeNo = "";//选择分类时,将原先的子类型清空
//                getData();
//            }
//        });
//        classPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                if ("分类".equals(binding.tvClassify.getText()) || "车型".equals(binding.tvClassify.getText())) {
//                    updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 0, null);
//                } else {
//                    updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 2, null);
//                }
//            }
//        });

        typePopWindow = new LeaseAskMapPopWindow(getActivity());
        typePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                updateChooseTextStatus(binding.typeLayout, binding.tvType, 2, ((PickSelectEntity) key1).getPickerViewText());
                typeNo = ((PickSelectEntity) key1).getNo();
                isLoadMore = false;
                page = 1;
                getData();
            }
        });
        typePopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if ("类型".equals(binding.tvType.getText()) || "品牌".equals(binding.tvType.getText())) {
                    updateChooseTextStatus(binding.typeLayout, binding.tvType, 0, null);
                } else {
                    updateChooseTextStatus(binding.typeLayout, binding.tvType, 2, null);
                }
            }
        });

        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setBgView(binding.grayLayout);
        mAddressPop.setMemberHeight();
        mAddressPop.setProvinceSingle();
        mAddressPop.setCitySingle();
        mAddressPop.setAreaMore();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnResultClick((key1, key2, key3) -> {
            try {
                List<BaseAreaEntity> listKey1 = (List<BaseAreaEntity>) key1;
                List<BaseAreaEntity> listKey2 = (List<BaseAreaEntity>) key2;
                List<BaseAreaEntity> listKey3 = (List<BaseAreaEntity>) key3;
                addrNo = "";
                if (listKey3 != null) {
                    for (int i = 0; i < listKey3.size(); i++) {
                        addrNo = addrNo + listKey3.get(i).getNo() + ",";
                    }
                }
                if (listKey2 != null && listKey2.size() > 0) {
                    cityNo = listKey2.get(0).getNo();
                    cityName = listKey2.get(0).getName();
                } else {
                    cityNo = "";
                }
                provinceNo = listKey1.get(listKey1.size() - 1).getNo();
                provinceName = listKey1.get(listKey1.size() - 1).getName();
            } catch (Exception exception) {
            }

            isLoadMore = false;
            page = 1;
            getData();
            if (!TextUtils.isEmpty(cityName) && "不限".equals(cityName)) {
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, cityName);
            } else {
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, 2, provinceName);
            }

        });
        mAddressPop.setOnDismissListener(() -> {
            updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? 0 : 2, null);
        });

        sortPopWindow = new DictWindow5(getActivity());
        sortPopWindow.setOnCallBack(new DictWindow5.OnCallBack() {
            @Override
            public void result(DictEntity3 dictEntity) {
                updateChooseTextStatus(binding.sortLayout, binding.tvSort, 2, dictEntity.getName());
                sortNo = dictEntity.getId();
                isLoadMore = false;
                page = 1;
                getData();
            }
        });
        sortPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                updateChooseTextStatus(binding.sortLayout, binding.tvSort, "排序".equals(binding.tvSort.getText()) ? 0 : 2, null);
            }
        });

    }

    private void initTabType() {
        //机械列表分类标题
        binding.tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                updateChooseTextStatus(binding.typeLayout, binding.tvType, 0, "品牌");
                typeNo = "";
                typePopWindow.goodsTypeAdapter.setDefItem(0);
                classNo = classDatas.get(tab.getPosition()).getNo();
                if (TextUtils.isEmpty(classNo)) {
                    typeDatas.clear();
                    PickSelectEntity entity = new PickSelectEntity();
                    entity.setNo("");
                    entity.setProjectscale("不限");
                    typeDatas.add(0, entity);
                } else {
                    int classIndex = tab.getPosition();
                    typeDatas.clear();
                    if ("2".equals(categoryType)) {
                        typeDatas.addAll(getCarByTypeData());
                    } else {
                        for (AskLeaseItemEntity ll : allDatas.get(classIndex - 1).getChildren()) {
                            PickSelectEntity child = new PickSelectEntity();
                            child.setNo(ll.getNo());
                            child.setProjectscale(ll.getName());
                            typeDatas.add(child);
                        }
                    }

                    PickSelectEntity entity = new PickSelectEntity();
                    entity.setNo("");
                    entity.setProjectscale("不限");
                    typeDatas.add(0, entity);
                }

                isLoadMore = false;
                page = 1;
                getData();
                showTypeTab();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


        binding.tabType.setTabMode(TabLayout.MODE_SCROLLABLE);
        binding.tabType.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                checkDismiss(0);
                typeNo = typeDatas.get(tab.getPosition()).getNo();
                isLoadMore = false;
                page = 1;
                getData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void initData() {
        if ("2".equals(categoryType)) {
            binding.tvClassify.setText("车型");
            binding.tvType.setText("品牌");
        }
        provinceNo = askLeaseFragModel.getAreaCodeModel();//默认省参数
        classDatas = new ArrayList<>();
        typeDatas = new ArrayList<>();
        showSortData();
        showClassPop();
        getData();
    }

    //因接口返回Json格式不规范,需要在此特别处理一级数据车型
    private void onResetCarByClassData() {
        classDatas.clear();
        for (AskLeaseItemEntity itemEntity : allDatas.get(0).getChildren()) {
            PickSelectEntity selectEntity = new PickSelectEntity();
            selectEntity.setNo(itemEntity.getNo());
            selectEntity.setProjectscale(itemEntity.getName());
            classDatas.add(selectEntity);
        }
    }

    //因接口返回Json格式不规范,转换二级数据品牌
    private List<PickSelectEntity> getCarByTypeData() {
        List<PickSelectEntity> tempData = new ArrayList<>();
        for (AskLeaseItemEntity itemEntity : allDatas.get(1).getChildren()) {
            PickSelectEntity selectEntity = new PickSelectEntity();
            selectEntity.setNo(itemEntity.getNo());
            selectEntity.setProjectscale(itemEntity.getName());
            tempData.add(selectEntity);
        }
        return tempData;
    }

    private void getData() {
        if (!TextUtils.isEmpty(addrNo)) {
            try {//如果字符串最后一位是逗号","则去掉最后一位
                Log.i("addrNo", addrNo);
                if (",".equals(addrNo.substring(addrNo.length() - 1))) {
                    addrNo = addrNo.substring(0, addrNo.length() - 1);
                }
            } catch (Exception ex) {
            }

        }

        askLeaseFragModel.getDataList(categoryType, classNo, typeNo, provinceNo, cityNo, addrNo, sortNo, page);
    }

    public void showList(List<AskLeaseSheBeiEntity> list) {
        binding.recyclerView.refreshComplete();
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (null != list && list.size() > 0) {
                askLeaseAdapter.addDatas(list);
            } else {
                binding.recyclerView.setNoMore(true);
            }
            binding.recyclerView.setVisibility(View.VISIBLE);
        } else {
            binding.recyclerView.refreshComplete();
            if (null != list && list.size() > 0) {
                binding.recyclerView.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                askLeaseAdapter.setDatas(list);
                binding.recyclerView.setNoMore(false);
            } else {
                askLeaseAdapter.setDatas(null);
                binding.recyclerView.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * @param v
     */
    @Override
    public void onClick(View v) {
        checkDismiss(v.getId());
        switch (v.getId()) {
//            case R.id.classify_layout:
//                if (null != classDatas && classDatas.size() > 0) {
//                    if ("分类".equals(binding.tvClassify.getText()) || "车型".equals(binding.tvClassify.getText())) {
//                        updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, -1, null);
//                    } else {
//                        updateChooseTextStatus(binding.classifyLayout, binding.tvClassify, 1, null);
//                    }
//                    classPopWindow.showPopwindow(binding.classifyLayout);
//                }
//                break;
            case R.id.type_layout:
                if (null != typeDatas && typeDatas.size() > 0) {
                    showTypePop();
                }
                break;
            case R.id.area_layout:
                updateChooseTextStatus(binding.areaLayout, binding.tvArea, "地区".equals(binding.tvArea.getText()) ? -1 : 1, null);
                mAddressPop.showPopwindow(binding.areaLayout);
                if (null == addressEntityList || addressEntityList.size() == 0) {
                    askLeaseFragModel.getCityData();
                }
                break;
            case R.id.sort_layout:
                if (null != sortDatas && sortDatas.size() > 0) {
                    updateChooseTextStatus(binding.sortLayout, binding.tvSort, "排序".equals(binding.tvSort.getText()) ? -1 : 1, null);
                    sortPopWindow.setCheckDefaultById(sortNo);
                    sortPopWindow.showPopwindow(binding.sortLayout);
                }
                break;
            default:
                break;
        }
    }

    private void showClassPop() {
        if ("2".equals(categoryType)) {//车辆求租
            onResetCarByClassData();
            binding.typeLayout.setVisibility(View.VISIBLE);
        } else {
            binding.typeLayout.setVisibility(View.GONE);
            for (AskLeaseItemEntity<List<AskLeaseItemEntity>> l : allDatas) {
                PickSelectEntity entity = new PickSelectEntity();
                entity.setNo(l.getNo());
                entity.setProjectscale(l.getName());
                classDatas.add(entity);
            }
        }

        if ("5".equals(categoryType)) {
            binding.typeLayout.setVisibility(View.GONE);
        }

        PickSelectEntity entity = new PickSelectEntity();
        entity.setNo("");
        entity.setProjectscale("全部");
        classDatas.add(0, entity);
//        classPopWindow.setData(classDatas);
//        classPopWindow.goodsTypeAdapter.setDefItem(0);

        for (int i = 0; i < classDatas.size(); i++) {
            binding.tabLayout.addTab(binding.tabLayout.newTab().setText(classDatas.get(i).getProjectscale()));
        }
        binding.tabLayout.selectTab(binding.tabLayout.getTabAt(0));
    }

    private void showTypePop() {
        if ("类型".equals(binding.tvType.getText()) || "品牌".equals(binding.tvType.getText())) {
            updateChooseTextStatus(binding.typeLayout, binding.tvType, -1, null);
        } else {
            updateChooseTextStatus(binding.typeLayout, binding.tvType, 1, null);
        }
        typePopWindow.showPopwindow(binding.typeLayout);
        typePopWindow.setData(typeDatas);
    }

    private void showTypeTab() {
        if (typeDatas == null || typeDatas.size() == 0) {
            binding.tabType.setVisibility(View.GONE);
            binding.viewTypeTabLine.setVisibility(View.GONE);
            return;
        }

        //设置类型tab
        if ("不限".equals(typeDatas.get(0).getProjectscale().trim())) {
            typeDatas.get(0).setProjectscale("全部");
            if (typeDatas.size() == 1) {
                binding.tabType.setVisibility(View.GONE);
                binding.viewTypeTabLine.setVisibility(View.GONE);
                return;
            } else if(!"2".equals(categoryType)){
                binding.tabType.setVisibility(View.VISIBLE);
                binding.viewTypeTabLine.setVisibility(View.VISIBLE);
            }
        }

        binding.tabType.removeAllTabs();
        for (int i = 0; i < typeDatas.size(); i++) {
            binding.tabType.addTab(binding.tabType.newTab().setText(typeDatas.get(i).getProjectscale()));
        }
        binding.tabType.selectTab(binding.tabType.getTabAt(0));
    }

    private void showSortData() {
        sortDatas = new ArrayList<>();
        sortDatas.add(new DictEntity3("1", "发布最近"));
        sortDatas.add(new DictEntity3("2", "发布最早"));
        sortDatas.add(new DictEntity3("3", "租期最长"));
        sortDatas.add(new DictEntity3("4", "租期最短"));
        sortPopWindow.setData(sortDatas);
        sortPopWindow.setCheckDefaultById("1");
    }

//    public void showAddressDatas(List<BaseAreaEntity<List<BaseAreaEntity>>> datas) {
//        this.cityDatas = datas;
//        if (datas == null || datas.size() == 0) return;
//        BaseAreaEntity baseAreaEntity = new BaseAreaEntity();
//        baseAreaEntity.setName("不限");
//        baseAreaEntity.setNo("");
//        baseAreaEntity.setChildren(new ArrayList<>());
//        datas.add(0, baseAreaEntity);
//        for (int i = 0; i < datas.size(); i++) {
//            datas.get(i).getChildren().add(0, baseAreaEntity);
//        }
//        areaWindow.setCityList(datas);
//        areaWindow.setCitySelectType(true);
//        areaWindow.setAreaSelectType(true, false);
//    }

    /**
     * 省市区数据信息
     *
     * @param data
     */
    public void showAddressDatas(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data, String provinceNo) {
        this.addressEntityList = data;
        if (data != null && data.size() > 0) {
            this.provinceNo = provinceNo;
            mAddressPop.setData(data, true, provinceNo);
        }
    }

    private void checkDismiss(int resId) {
        if (mAddressPop != null && mAddressPop.isShowing() && R.id.area_layout != resId) {
            mAddressPop.dismiss();
        }
    }


    //更新选项颜色
    private void updateChooseTextStatus(View view, TextView textView, int value, String name) {
        if (value == 0) {
            setTextViewBg(view, textView, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
        } else if (value == -1) {
            setTextViewBg(view, textView, R.drawable.search_bg, R.mipmap.ic_up_arrow_n, R.color.color_333333);
        } else if (value == 1) {
            setTextViewBg(view, textView, R.drawable.search_new_blue_bg, R.mipmap.icon_up_red, R.color.color_main);
        } else if (value == 2) {
            setTextViewBg(view, textView, R.drawable.search_new_blue_bg, R.mipmap.icon_down_red, R.color.color_main);
        }
        if (TextUtils.isEmpty(name)) return;
        textView.setText(name);
    }

    //设置背景色和图标
    private void setTextViewBg(View view, TextView textView, int bg, int img, int textColor) {
        view.setBackgroundResource(bg);
        Drawable drawable_n = getResources().getDrawable(img);
        drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());
        textView.setCompoundDrawables(null, null, drawable_n, null);
        textView.setTextColor(getResources().getColor(textColor));
    }

    //提供给外部调用
    public void onLoadMore() {
        page = page + 1;
        isLoadMore = true;
        getData();
    }
}
